package com.example.zdxk.controller;

import com.example.zdxk.Decoder.SendDecoder;
import com.example.zdxk.entity.*;
import com.example.zdxk.netty.TcpServer;
import com.example.zdxk.service.*;
import com.example.zdxk.util.BaiduAPI;
import com.example.zdxk.util.DateUtils;
import com.example.zdxk.util.FormatUtil;
import com.example.zdxk.util.LayuiData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Controller
public class TermController {
    @Autowired
    private TermService termService;
    @Autowired
    private LocationService locationService;
    @Autowired
    private SettingService settingService;

    public  String set;
    public String set()
    {
        return set;
    }
    public int termid;


    @RequestMapping("/getSettingList")
    @ResponseBody
    public LayuiData getSettingList (HttpServletRequest request){
        String imei = request.getParameter("imei");
        if(imei==null) {
            imei = "";
        }
        int page = Integer.parseInt(request.getParameter("page"));
        int limit = Integer.parseInt(request.getParameter("limit"));
        if(page>=2){
            page = (page-1)*limit;
        }
        LayuiData layuiData = new LayuiData();
        List<Setting> settingList = settingService.getsettingList(imei,page,limit);
        //int count = terminfoService.getTerminfocount();
        layuiData.setCode(0);
        layuiData.setCount(10);
        layuiData.setMsg("数据请求成功");
        layuiData.setData(settingList);
        return layuiData;
    }

    @RequestMapping("/settinglist")
    public String settingList() {
        System.out.println("settinglist");
        return "settingListPage";
    }
    @RequestMapping("/settingAdd")
    @Transactional
    @ResponseBody
    public Integer settingAdd (String imei,String setting, String meg_id){
        System.out.println("settingAdd");
        Setting xixunSetting= new Setting();
        xixunSetting.setImei(imei);
        xixunSetting.setSetting(setting);
        xixunSetting.setSubmitTime(DateUtils.getTime());
        xixunSetting.setMeg_id(meg_id);
        int num = settingService.add(xixunSetting);
        System.out.println(xixunSetting.getImei());
        System.out.println(xixunSetting.getSetting());
        System.out.println(xixunSetting.getSubmitTime());
        System.out.println(xixunSetting.getConfirm());
        return num;
    }

    @RequestMapping("/toSetting")
    public String toSetting(){
        System.out.println("toSetting");
        return "settingAdd";
    }
    @RequestMapping("/toUpdate")
    public String toUpdatesetting(Integer sid, Model model) {
        Setting xixunSetting=settingService.getSettingBySid(sid);

        model.addAttribute("xixunSetting",xixunSetting);
        return "settingUpdate";
    }
    /**
     * 根据id修改用户信息
     * @return
     */
    @RequestMapping("/settingUpdate")
    @Transactional
    @ResponseBody
    public Integer settingUpdate (Integer sid,String setting){
        System.out.println("settingUpdate");
        Setting xixunSetting=new Setting();
        //xixunSetting1.setImei(imei);
        xixunSetting.setSetting(setting);
        xixunSetting.setSid(sid);
        xixunSetting.setSubmitTime(DateUtils.getTime());




        int num =settingService.update(xixunSetting);
        return num;
    }

    @RequestMapping("/settingDelete")
    @ResponseBody
    public Integer deletesetting(Integer sid) {

        int num = settingService.delete(sid);

        return num;
    }






    @RequestMapping("/getTerminfoList")
    @ResponseBody
    public LayuiData getTerminfoList (HttpServletRequest request){
        String term_imei = request.getParameter("term_imei");
        int page = Integer.parseInt(request.getParameter("page"));
        int limit = Integer.parseInt(request.getParameter("limit"));
        if(page>=2){
            page = (page-1)*limit;
        }




        LayuiData layuiData = new LayuiData();
        List<Term> termlist = new ArrayList();
        if(term_imei==null)
        {
            List<Term> terminfoList = termService.getTerminfoList( page, limit);
            int count = termService.getTerminfoList2().size();


            // int count = terminfoService.getTerminfocount();
            for (Term terminfo : terminfoList) {
                Term term = new Term();
                term.setId(terminfo.getId());
                term.setterm_imei(terminfo.getterm_imei());
                if (terminfo.getterm_provider() == 1)
                    term.setterm_provider(3);
                else if (terminfo.getterm_provider() == 2)
                    term.setterm_provider(2);
                term.setregister_time(terminfo.getregister_time());
                term.setbatvalue(terminfo.getbatvalue());
                term.setchainstate(terminfo.getchainstate());

                Location location = locationService.getlocation(terminfo.getterm_imei());
                if (location != null) {
                    term.setlocation_lat(location.getlocation_lat());
                    term.setlocation_lng(location.getlocation_lng());
                    term.setlocation_name(location.getlocation_name());
                    term.setlocation_time(location.getlocation_time());
                    term.setlocation_type(location.getLocation_type());

                }

                termlist.add(term);


            }
            layuiData.setCode(0);
            layuiData.setCount(count);
            layuiData.setMsg("数据请求成功");
            layuiData.setData(termlist);
            return layuiData;
        }
        else
        {
            Term terminfo=termService.getTerminfoByImei(term_imei);
            if(terminfo==null) {

                layuiData.setCode(0);
                layuiData.setCount(termlist.size());
                layuiData.setMsg("数据请求成功");
                layuiData.setData(termlist);
                return layuiData;
            }
            else{
                Term term=new Term();
                term.setId(terminfo.getId());
                term.setterm_imei(terminfo.getterm_imei());
                if (terminfo.getterm_provider() == 1)
                    term.setterm_provider(3);
                else if (terminfo.getterm_provider() == 2)
                    term.setterm_provider(2);
                term.setregister_time(terminfo.getregister_time());
                term.setbatvalue(terminfo.getbatvalue());
                term.setchainstate(terminfo.getchainstate());

                Location location = locationService.getlocation(terminfo.getterm_imei());
                if (location != null) {
                    term.setlocation_lat(location.getlocation_lat());
                    term.setlocation_lng(location.getlocation_lng());
                    term.setlocation_name(location.getlocation_name());
                    term.setlocation_time(location.getlocation_time());
                    term.setlocation_type(location.getLocation_type());
                }

                termlist.add(term);
                layuiData.setCode(0);
                layuiData.setCount(termlist.size());
                layuiData.setMsg("数据请求成功");
                layuiData.setData(termlist);
                return  layuiData;



            }
        }
    }

    /**
     * 去新增用户界面
     * @return
     */
    @RequestMapping("/toTerminfo")
    public String toTerminfo (){

        return "terminfoAdd";
    }
    @RequestMapping("/List")
    public String Terminfolist (Model model){
        List<Term> terminfoList = termService.getTerminfoList(1,1);
        model.addAttribute("terminfoList",terminfoList);
        return "terminfoList";
    }


    @RequestMapping("/terminfoAdd")
    @Transactional
    @ResponseBody
    public Integer terminfoAdd (String term_imei,Integer term_provider){
        Term terminfo = new Term();
        Date day=new Date();

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //terminfo.setenter_time(df.format(day));
        terminfo.setterm_imei(term_imei);
        terminfo.setterm_provider(term_provider);
        int num = termService.add(terminfo);
        return num;
    }

    @RequestMapping("/terminfodelete")
    @ResponseBody
    public Integer terminfodelete(Integer id) {

        int num = termService.delete(id);

        return num;
    }
    @RequestMapping("/terminfoListpage")
    public String terminfoListpage() {

        return "terminfoListPage";
    }




    /**
     * 根据id修改用户信息
     * @return
     */
    @RequestMapping("/terminfoUpdate1")
    @Transactional
    @ResponseBody
    public Integer terminfoUpdate (Integer id,Integer bind_type){
        Term terminfo = termService.getTerminfoById(id);
        System.out.println(terminfo.getterm_imei());
        System.out.println(bind_type);
        if(bind_type==0) {
            System.out.println("update 0");
            //terminfo.setbind_type(0);

            int num = termService.update(terminfo);
            System.out.println(num);
            return num;
        }
        else
        {
            System.out.println("update 1");
            //terminfo.setbind_type(1);

            int num = termService.update(terminfo);
            System.out.println(num);
            return num;
        }
    }

    /**
     * 去修改界面
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/totermUpdate")
    public String totermUpdate(Integer id, Model model) {

        Term term = termService.getTerminfoById(id);

        System.out.println("toupdate");
        model.addAttribute("term", term);
        // model.addAttribute("terminfo",terminfo);
        return "terminfoUpdate";

    }

    @RequestMapping("/terminfoUpdate")
    @Transactional
    @ResponseBody
    public int send1(Integer id,Integer if_chain,Integer upload_intervel)
    {   System.out.println(id+if_chain+upload_intervel);
        Term term= termService.getTerminfoById(id);
        if(if_chain==1||if_chain==0)
        {
            term.setif_chain(if_chain);
        }
        if(upload_intervel<=60&&upload_intervel>0)
        {
            term.setupload_intervel(upload_intervel);
        }
        term.setif_upload(0);
        termService.update(term);
        return 1;


    }


    /**
     * 去查看界面
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/terminfoDetail")
    public String terminfoDetail(Integer id, Model model) {

        Term terminfo = termService.getTerminfoById(id);
        return "settingListPage";
//        if(terminfo.getterm_provider()==2) {                        //设备类型为前海
//            System.out.println("terminfoDetail");
//            return "settingListPage";
//        }
//        else {
//            System.out.println("没进terminfoDetail");
//            LeadcentMessage leadcentMessage=new LeadcentMessage();
//            leadcentMessage.setImei(terminfo.getterm_imei());
//            leadcentMessage.setType("1002");
//            leadcentMessage.setContent0("600");
//            model.addAttribute("leadcentMessage", leadcentMessage);
//            return "terminfoDetail";
//        }
    }
    @RequestMapping("/location")
    public String location(Integer id, Model model) {

        return "getLocationList?id="+id;
    }

    /**
     * 去位置信息界面
     * @param id
     * @return
     */
    @RequestMapping("/toLocation")
    public String terminfoDetail(Integer id) {

        //LeadcentMessage leadcentMessage=new LeadcentMessage();
        // leadcentMessage.setImei(terminfo.getterm_imei());
        //leadcentMessage.setType("1002");
        //leadcentMessage.setContent0("600");
        // model.addAttribute("leadcentMessage", leadcentMessage);
        termid=id;
        System.out.println(id);
        return "locationListPage";

    }

    /**
     * 获取设备位置表
     * @param request
     * @return
     */
    @RequestMapping("/getLocationList")
    @ResponseBody
    public LayuiData getLocationList (HttpServletRequest request){
        String term_imei = termService.getTerminfoById(termid).getterm_imei();
        System.out.println(term_imei);
        int page = Integer.parseInt(request.getParameter("page"));
        int limit = Integer.parseInt(request.getParameter("limit"));
        if(page>=2){
            page = (page-1)*limit;
        }

        LayuiData layuiData = new LayuiData();
        List<Location> locationList =locationService.getLocationList(term_imei,page,limit);
        int count=locationService.getLocationcount(term_imei).size();
        layuiData.setCode(0);
        layuiData.setCount(count);
        layuiData.setMsg("数据请求成功");
        layuiData.setData(locationList);
        return layuiData;


    }








    //--------------------主动发送消息------------------------

    @RequestMapping("/edit")
   // @Transactional
   // @ResponseBody
    public String doedit(){
        System.out.println("do it！！！！！");
        return "Edit";
    }



    @RequestMapping("/send2")       //长连接发送方式
    @Transactional
    @ResponseBody
    public int send2(String id, String imei, String content)       //直接传参过来, imei 2位一个字节
    {
        System.out.println("消息id: "+id);
        System.out.println("imei: "+imei);
        System.out.println("content: "+ content);
        //byte[] id = {(byte)0x07, (byte)0x81};                   //查询终端属性
        byte[] mes = SendDecoder.toData(FormatUtil.hexStringToBytes(id), FormatUtil.hexStringToBytes(imei), FormatUtil.hexStringToBytes(content)	);

        TcpServer server = new TcpServer();
        boolean i =server.sendMessage(imei,mes);

        if(i){
            System.out.println("发送成功！");
            System.out.println("发送的消息："+ DatatypeConverter.printHexBinary(mes));
            return 1;
        }
        else {
            System.out.println("发送失败！该设备没链接");
            return 0;
        }
    }


}
